package com.xqcx.libra.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class AbstractThreadHandler implements ThreadHandler {

	private Thread thread = new Thread(this);

	private volatile boolean run = true;

	private final Log log = LogFactory.getLog(this.getClass());

	protected abstract void handle();

	public final void start() {
		this.thread.setName(this.getClass().getSimpleName());
		this.thread.start();
	}

	@SuppressWarnings("static-access")
	public final void sleep(long millis) {
		synchronized (thread) {
			try {
				this.thread.sleep(millis);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	public final void stop() {
		this.run = false;
	}

	public final void resume() {
		synchronized (thread) {
			this.thread.notify();
		}
	}

	protected final void suspend() {
		synchronized (thread) {
			try {
				this.thread.wait();
			} catch (InterruptedException e) {
				log.error("failed to suspend", e);
			}
		}
	}

	protected final void suspend(long millis) {
		synchronized (thread) {
			try {
				this.thread.wait(millis);
			} catch (InterruptedException e) {
				log.error("failed to suspend", e);
			}
		}
	}

	public final void run() {
		while (run) {
			try {
				handle();
			} catch (Throwable e) {
				log.error("failed to run", e);
			}
		}
	}

}
